<?

class i18n_update_task extends system_task
{
	private $phrases = array();
	public function execute( array $params = array() )
	{
		$this->get_phrases(PROJECT_PATH);
		$this->out();
		$this->out('Total: ' . count($this->phrases) . ' phrases');

		$languages = config::all()->i18n['languages'];
		$languages = array_diff($languages, array(i18n::src_language()));

		if ( !$languages ) return $this->error('No languages are configured in config.i18n.languages');

		foreach ( $languages as $language ) $this->update_language( $language );
	}

	private function get_phrases( $root )
	{
		$d = opendir($root);
		while ( $f = readdir($d) )
		{
			if ( in_array($f, array('.', '..', '.svn')) ) continue;

			if (strpos($root, 'web/public') ) continue;

			if ( is_dir($root . '/' . $f) )
				$this->get_phrases ($root . '/' . $f);
			else
				$this->parse_file( $root . '/' . $f );
		}
	}

	private function parse_file( $path )
	{
		if ( $exclude = config::all()->i18n['exclude'] )
			foreach ( $exclude as $expath ) if (strpos($path, $expath) ) return;

		echo '.';
		$content = file_get_contents($path);

		preg_match_all('/_\(\'(.+?)\'[),]/ms', $content, $m);
		foreach ( $m[1] as $phrase )
		{
			$phrase = str_replace('\\\'', '\'', $phrase);
			$this->phrases[$phrase] = true;
		}

		if ( strpos($content, 'class') && strpos($content, 'static') )
		{
			if ( preg_match_all('/[ \t]+[a-z0-9\']+ => \'(.+?)\'/usi', $content, $m) )
			{
				foreach ( $m[1] as $phrase ) $this->phrases[$phrase] = true;
			}
		}
	}

	private function update_language( $language )
	{
		$this->out("\n");
		$this->out('Updating ' . $language . '...');
		$translations = i18n::get_translations($language);

		foreach ( $this->phrases as $phrase => $flag )
		{
			if ( preg_match('/^[0-9 \t,\']+$/m', $phrase) ) continue;
			if ( ($language == 'en') && preg_match('/^[a-z A-Z\-@<>="\/\.,:0-9]+$/', $phrase) ) continue;
			
			$new_translations[$phrase] = $translations[$phrase];
		}

		foreach ( $new_translations as $phrase => $translation )
			if ( !$translation ) $to_translate[] = $phrase;

		if ( $to_translate )
		{
			$this->out('Translating ' . count($to_translate). ' phrases...');

			foreach ( $to_translate as $src )
			{
				echo '.';
				
				$tr = translate_by_google(i18n::src_language() . "|{$language}", $src);
				$this->out( $src . ': ' . $tr );
				
				$new_translations[$src] = $tr;
				
				mt_rand(0, 5) == 3 ? sleep(1) : null;
			}
		}

		i18n::store_translations($language, $new_translations);

		$this->out('ok');
	}
	
	public function unicode_decode($str){
		return preg_replace("/\\\u([0-9A-F]{4})/ie", "iconv('utf-16', 'utf-8', hex2str(\"$1\"))", $str);    
	}
}

function translate_by_google( $langpair, $text )
{
	$url = "http://ajax.googleapis.com/ajax/services/language/translate?v=2.0&langpair=".urlencode($langpair);
	$c = curl_init( $url );
	curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($c, CURLOPT_POST, true);
	curl_setopt($c, CURLOPT_REFERER, "http://www.google.com");
	$post = '&q=' . urlencode($text);
	curl_setopt($c, CURLOPT_POSTFIELDS, $post);

	$data = curl_exec($c);  
	$data = json_decode($data);

	return _html_entity_decode($data->responseData->translatedText);
}

function _html_entity_decode($string) {
	$string = html_entity_decode($string);
	$string = str_replace('&#39;', "'", $string);
	$string = str_replace('% s', "%s", $string);
	return $string;
}